package com.zhang.table;

import com.zhang.second.utils.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @title:
 * @author: zhang
 * @date: 2022/2/10 15:49
 */
public class StreamToTableAgg {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<SensorReading> sensorReadingDS = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, SensorReading>() {
                    @Override
                    public SensorReading map(String value) throws Exception {
                        String[] fields = value.split(" ");
                        return new SensorReading(
                                fields[0], Integer.parseInt(fields[1])
                        );
                    }
                });

        //获取流表环境
        StreamTableEnvironment streamTableEnvironment = StreamTableEnvironment.create(env);

        //将流转换为动态表
        Table sensorTable = streamTableEnvironment.fromDataStream(sensorReadingDS);

        //使用table api实现 select  sensorId,sum(temperature) from sensorTable where temperature >= 20 group by sensorId
        Table result = sensorTable
                .where($("temperature").isGreaterOrEqual(20))
                .groupBy($("sensorId"))
                .aggregate($("temperature").sum().as("sum_temp"))
                .select($("sensorId"), $("sum_temp"));

        //将表转化为流打印
        DataStream<Tuple2<Boolean, Row>> retractStream = streamTableEnvironment.toRetractStream(result, Row.class);
        retractStream.print();

        env.execute();
    }
}
